
webix.ready(function(){
webix.ui.fullScreen();
  var my_template={
    template: "<span style='font-size:20px; font-weight:bold; color:#3498DB'; >刀具库管理</span>&nbsp;/&nbsp;&nbsp; CutterManager",
    height:45,
    borderless:true 
  };
  var my_table={
        view:"datatable",
        id:"mydatatable",
        columns:[
          {id:"material_id",header:"系统编码",fillspace:true},
          {id:"customer_specs_no",header:"客户物料编码",fillspace:true},
          {id:"long_specs_cust",header:"规格",fillspace:true,editor:"text"},
          {id:"simple_specs_cust",header:"规格简称",fillspace:true,editor:"text"},
          {id:"supp_name",header:"供应商",fillspace:true,editor:"text"},
          {id:"safeNum",header:"安全数量",fillspace:true,editor:"text"},
          {id:"operate",header:"使用寿命区间",fillspace:true,template:"<div><a href='#' onclick=\"addCutterSpecsIntervalShow('#material_id#');\">查看</a></div>"}
        ],
        height:600,
        select:true,
        // url:"http://192.168.1.111:9001/Application/demo"
      };
      var my_toolbar={
        view:"toolbar",
        elements:[           
          {
            view:"text",
            id:"s1",
            label:"刀具规格:",
            width:300
          },
          {
            view:"text",
            id:"s2",
            label:"供应商名称:",
            labelWidth:135,
            width:300
          },
          {
            view:"text",
            id:"s3",
            label:"客户编码:",
            width:300
          },
          {view:"button",value:"查询",width:50,click:"select",css:"btn_check"}
        //  {view:"button",value:"添加刀具",width:80,click:"addRow",css:"btn_check"},
       //   {view:"button",value:"确认添加",width:80,click:"confirm",css:"btn_check"},
       //   {view:"button",value:"保存修改",width:80,click:"save",css:"btn_check"},
       //   {view:"button",
	  //          template:"<form class='am-form' id='myform' action='upload' method='post' enctype='multipart/form-data'>" +
		//        "<input style='margin-left: 4px; width: 165px; height: 32px;' name='myfile' id='upload' accept='application/vnd.ms-excel' type='file' style='float:left;'> " +
		//        "<input class='webixtype_base'style='margin-left: 4px; width: 80px; height: 32px;'  id='search_sub' type='button' onclick='submitExcel()' value='确认上传'> " +
		//        "</form>",
	  //          css:"btn_check",
	  //          width:265
	   //    },
     //   {view:"button",value:"导出模板",width:80,click:"download()",css:"btn_check"},
        ]   
      };
    var page={
            view:"pager",
            id:"pagerA",
           //新用户刚开始没有产生数据出现分页标签
		   // count:1000,
			//master:false,
			//group:15,
			//size:5,
			//page:1,
            template:"{common.first()}{common.prev()}{common.pages()}{common.next()}{common.last()}",
            css:"pager",
            on: {
                  onItemClick: function(id, e, node){
                   if (id == "next") {
                    if($$("pagerA").config.limit==$$("pagerA").config.page+1)
                      {
                        id = $$("pagerA").config.limit-1;
                      }
                      else
                      {
                        id=$$("pagerA").config.page+1;
                      }
                    }
                  else if(id=="prev")
                  {
                    id=$$("pagerA").config.page-1; 
                  }
                  else if(id=="first")
                  {
                    id=0;
                  }
                  else if(id=="last")
                  {
                    id=$$("pagerA").config.limit-1;
                  } 
                  var params={};
                  params.currPage =parseInt(id)+1;
                  params.pageSize =10;
                  postData("getCutterList", params,callback);
                }
            },
            height:38,
            css:{"text-align": "center","margin-top":"20px!important"}
        };
    var params={};
    params.pageSize =10;
    postData("getCutterList", params,callback);
  var web={
    container:"body",
    type:"line",
    id:"mylayout",
    rows:[
        my_template,
        my_toolbar,
        my_table,
        page
    ],
  };
  webix.ui(web);// ---webix.ui结束----
$$("s1").attachEvent("onTimedKeyPress", function(){
	var value1 = this.getValue();
	var name2=$$("s2").getValue();
	var name3=$$("s3").getValue();
   if(value1==""&&name2==""&&name3==""){
    location.reload();
    }
  });  
$$("s2").attachEvent("onTimedKeyPress", function(){
	var value2 = this.getValue();
	var name1=$$("s1").getValue();
	var name3=$$("s3").getValue();
   if(value2==""&&name1==""&&name3==""){
    location.reload();
    }
  });  
  $$("s3").attachEvent("onTimedKeyPress", function(){
	var value3 = this.getValue();
	var name2=$$("s2").getValue();
	var name1=$$("s1").getValue();
   if(value3==""&&name2==""&&name1==""){
    location.reload();
    }
  });  
 
//------------------  添加使用寿命区间   start------------------------
	var addForm = [ {
		id:"addMill",
		view : "button",
		value : "添加",
		width : 80,
		click : "addRows",
		css : {
			"margin-left" : "380px!important"
		}
	},{
	    view:"datatable",
	    id:"my_pro_dt",  
	    width:300, 
	    height:300, 
	    columns:[
	      {id:"startNum",header:"起始数",editor:"text",width:180},
	      {id:"endNum",header:"终止数",editor:"text",width:180},
	      {
	          id: "operate",
	          header: "操作",
	          width: 80,
	          tooltip: false,
	          fillspace: true,
	          template: "<button class='delbtn1 style'>删除</button>"
	      }/* {common.trashIcon()}删除 */
	    ],  
	    onClick: {// 删除规格寿命事件
	      "delbtn1": function(e, id, trg) {// list_index指选中的工序
	    	  $$("my_pro_dt").editStop();
	          $$("my_pro_dt").remove(id); 
	        return false;
	      } 
	    },     
	    select:true,
	    data:"",
	    editable:true,
	    tooltip:true
	  },{
		id:"addSub",
		view : "button",
		value : "确定",
		width : 80,
		click : "addSub",
		css : {
			"margin-left" : "380px!important"
		}
	} ];
	var head = {
		view : "toolbar",
		margin : -4,
		cols : [ {
			view : "label",
			label : "查看使用寿命区间"
		}, {
			view : "icon",
			icon : "times-circle",
			click : "$$('win3').hide();"
		} ]
	};
	var body = {
		view : "form",
		id : "form",
		autoheight : true,
		width : 500,
		margin : 20,
		elements : addForm
	};
	var addMarkWindow = new webix.ui({
		view : "window",
		id : "win3",
		position : "center",
		modal : true,
		move : true,
		head : head,
		body : body
	});
	//------------------  添加打标计划窗口   end------------------------
})

function callback(data){
  var text1=JSON.parse(data); 
  //var data = new webix.DataCollection({data:text1.page});
  //$$('mydatatable').data.sync(data);
  //廖利红修改（跳页添加报错问题）
  $$("mydatatable").clearAll();
  $$("mydatatable").define("data",text1.page);
  $$('mydatatable').refresh();
  $$("pagerA").define("limit",text1.totalPageCount);
  $$("pagerA").define("count",text1.totalCount);
  $$("pagerA").define("size",text1.pageSize);
  $$("pagerA").define("page",text1.currPage-1);
  $$('pagerA').refresh();
}
var flag=true;
// 行id
var row;
// 添加一行
function addRow(){ 

var dt=$$("mydatatable");
if(flag){
 var id=dt.add({
 }); 
 row=id;
 console.log(row);
 dt.addRowCss(id, "newRow");
 dt.editRow(id);
 flag=false;
}else{
 alert("请完成当前刀具添加");
 console.log(row);
 dt.editRow(row);
}
// var newPg=++text1.pageSize;
// $$("pagerA").define("size",newPg);
// dt.editRow(id);
};
function delRow(material_id){
	    webix.confirm({
	        title:"提示",
	        text:"确定要删除吗?",
	        ok:"确定", 
	        cancel:"取消",
	        callback:function(result){
	        	if(result==true){
	        	var params = {};
	    		params.material_id = material_id;
	    		webix.ajax().post("delCutter", params, function(text, xml, xhr){
	    			alert("执行完毕");
	    			location.reload();
	    	 });
	        	}
	        }
	        });
	 
};
// 获取表格值并刷新
function confirm(){
  var dt=$$("mydatatable");
  dt.editStop();   
  dt.eachRow(function(row){
    if(dt.hasCss(row,"newRow")==true){
      params=dt.getItem(row);
        if(params.cutter_specs==""){
          alert("请填写规格...");
           dt.editRow(row);
          return false;
        }else if(params.supp_name==""){
          alert("请填写供应商名称...");
          dt.editRow(row);
          return false;
        }else if(params.simple_specs_cust==""){
          alert("请填写规格简称...");
          dt.editRow(row);
          return false;
        }else if(params.cust_cutter_spesc_id==""){
          alert("请填写客户编码...");
          dt.editRow(row);
          return false;
        }else if(params.safeNum==""){
          alert("请填写安全数量...");
          dt.editRow(row);
          return false;
        }else{
       	 webix.ajax().post("addCutter", params, function(text, xml, xhr){
  			alert("执行完毕");
  			location.reload();
     	 	});
        }
        dt.removeRowCss(row, "newRow");
     }    
  });
  // var originalPg=text1.pageSize;
  // alert(oldsize);
  // $$("pagerA").define("size",oldsize);
  // postData("http://192.168.1.111:9001/Application/demo", params,callback2);

}
// 查询实现
function select(){
 var params = {};
  var s1=$$("s1").getValue();
  var s2=$$("s2").getValue();
  var s3=$$("s3").getValue(); 
  params.cust_cutter_spesc_id=s3;
  params.supp_name = s2;
  params.cutter_specs = s1;
  // alert(params);
  postData("getCutterList",params,callback);
  
}
function edit(gg){
  console.log(gg);
  if(gg){
	  var dt=$$("mydatatable");
	  dt.eachRow(function(row){
		if(dt.getItem(row).material_id==gg){
		  dt.editRow(row);
		  dt.addRowCss(row, "newRow2");
		}    
	  });
  }
}
function save(){
  var dt=$$("mydatatable");
  dt.editStop();   
  dt.eachRow(function(row){
    if(dt.hasCss(row,"newRow2")==true){
      params=dt.getItem(row);
	 if(params.cutter_specs==""){
          alert("请填写规格...");
           dt.editRow(row);
          return false;
        }else if(params.supp_name==""){
          alert("请填写供应商名称...");
          dt.editRow(row);
          return false;
        }else if(params.simple_specs_cust==""){
          alert("请填写规格简称...");
          dt.editRow(row);
          return false;
        }else if(params.cust_cutter_spesc_id==""){
          alert("请填写客户编码...");
          dt.editRow(row);
          return false;
        }else if(params.safeNum==""){
          alert("请填写安全数量...");
          dt.editRow(row);
          return false;
        }else{
		  dt.removeRowCss(row, "newRow2");
		  console.log(params);
		  webix.ajax().sync().post("editCutter", params, function(text, xml, xhr){
			  console.log(params);
		  });
		  alert("执行完毕");
		location.reload();
		}
    }
  });
}
//上传excel
function submitExcel(){
	
	var excelFile = $("#upload").val();
    if(excelFile=='') {
    	alert("请选择需上传的文件!");
    	return false;
    }
    
    if(excelFile.indexOf('.xls')==-1){
    	alert("文件格式不正确，请选择正确的Excel文件(后缀名.xls)！");
    	return false;
    }
    
    $("#search_sub").attr("disabled",true);
    $("#search_sub").css({"backgroundColor":"#BBBBBB"})
    $("#myform").submit();
    
}

// 导出模板
function download(){
	window.location.href ="download";
}

//添加使用寿命区间
function addCutterSpecsIntervalShow(material_id){ 
	$("#edit_material_id").val(material_id);
	
	$$('win3').show();
	var params ={"material_id" : material_id}
	webix.ajax().sync().post("getCutterSpecsInterval", params, function(text, xml, xhr) {
		 var rs = JSON.parse(text);
		 if(rs.ret == "1000"){
			 var data = JSON.parse(rs.data);
			 $$("my_pro_dt").clearAll();
			 $$("my_pro_dt").define("data",data.data);
			 $$("my_pro_dt").refresh();
         }else{
        	 alert("获取寿命区间失败");
        	 location.reload();
         }
	});
	
};

/* 点击“添加”按钮添加一行 */
function addRows(){ 
  var dt=$$("my_pro_dt");  
  dt.enable();
  var id = dt.add({
  });
  dt.select(id);
  dt.editRow(id);
}

// 提交使用寿命区间
function addSub(){
	$$("addSub").disable();
	var num = 0;
	var start_judge=[];
	var end_judge=[];
	var start_nullValue=0;
	var end_nullValue=0;
	var csiList = [];
	/* 表格数据 */
	$$("my_pro_dt").eachRow( function (row){
		var dt=$$("my_pro_dt");
		start_judge.push(dt.getItem(row).startNum);
		end_judge.push(dt.getItem(row).endNum);
	});
	
	/* start_judge空值（""）数量 */
	for(var i=0;i<start_judge.length;i++){
		var re = /^[1-9]+[0-9]*]*$/;
		if (!re.test(start_judge[i]) && start_judge[i] != "0"){
			$$("addSub").enable();
			alert("起始数请输入正整数");  
		    return false;  
		}
		if((start_judge[i]==undefined||start_judge[i]=="") && start_judge[i]!="0"){
			console.log(start_judge[i]);
			start_nullValue++;
	    }
	};
	/* end_judge空值（""）数量 */
	for (var i = 0; i < end_judge.length; i++) {
		var re = /^[1-9]+[0-9]*]*$/;
		if (!re.test(end_judge[i])){
			$$("addSub").enable();
			alert("终止数请输入正整数");  
		    return false;  
		}
		if(end_judge[i]==undefined||end_judge[i]==""){
			end_nullValue++;
	    }
	};
	if(start_nullValue>0 || end_nullValue>0){
		webix.alert({
		      title:"警告",
		      text:"当前数据存在空值，请检查起始数，终止数！！",
		      ok:"确定",
		      type:"confirm-warning",
		      callback:function(result){
		        if(result==true){
		        }
		      }
		});
		$$("addSub").enable();
		return false;
	}else{
		$$("my_pro_dt").eachRow( function (row){
			var dt=$$("my_pro_dt");
			csiList[num] = {
	        		startNum: dt.getItem(row).startNum,
		            endNum: dt.getItem(row).endNum
		        };
			num++;
		});
	}
	var edit_material_id = $("#edit_material_id").val();
	
	var reData ={"reData" : JSON.stringify(csiList),"material_id" : edit_material_id}
	webix.ajax().sync().post("addCutterSpecsInterval", reData, function(text, xml, xhr) {
		 if(text == "success"){
        	 alert("保存成功");
        	 location.reload();
         }else{
        	 alert("保存失败");
        	 location.reload();
         }
		 
	});
}
